package com.bzy.blp.interceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bzy.common.bean.Result;
import com.bzy.common.bean.Result.Result_Code;
import com.bzy.common.util.HttpServletUtil;
import com.bzy.common.util.LoggerUtil;
import com.bzy.common.util.StringUtil;
import com.bzy.common.util.local.ThreadLocalUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class UserBaseHandlerInterceptor implements HandlerInterceptor {

	private static String ACCESS_UID = "current_login_uid";
	private static String OBJECT_TYPE = "object_type";
	private static String OBJECT_ID = "object_id";

	private List<String> excludesUrl = new ArrayList<String>();

	private Map<String, List<String>> allowIps = new HashMap<String, List<String>>();

//	@Resource
//	TblLogSystemUserAccessRecordDatMapper tblLogSystemUserAccessRecordDatMapper;

	public Map<String, List<String>> getAllowIps() {
		return allowIps;
	}

	public void setAllowIps(Map<String, List<String>> allowIps) {
		this.allowIps = allowIps;
	}

	public List<String> getExcludesUrl() {
		return excludesUrl;
	}

	public void setExcludesUrl(List<String> excludesUrl) {
		this.excludesUrl = excludesUrl;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// execute no.1
		ThreadLocalUtil.setRunTime(System.currentTimeMillis());
		Boolean isAuthenticated = ThreadLocalUtil.getIsAuthenticated();
		LoggerUtil.info(HttpServletUtil.getRequestLog(request, null, isAuthenticated));
		if (isAuthenticated == null || isAuthenticated == true) {
			String requestPath = request.getPathInfo();
			if (StringUtil.isBlank(requestPath)) {
				requestPath = request.getServletPath();
			}
			isAuthenticated = true;
		} else {
			Result result = null;
			Map<String, Object> infoMap = new HashMap<>();
			String type = request.getHeader("from");
			if (StringUtil.isBlank(type)) {
				type = request.getParameter("from");
			}
			if (StringUtil.isBlank(type)) {
				result = new Result(Result_Code.err_unknown);
			} else {
				String hrefPrefix = "http://wux.jites.com.cn/wuxcms/login.html";
				infoMap.put("href", hrefPrefix + "?type=" + type);
				infoMap.put("type", type);
				result = new Result(Result_Code.err_notLogin);
				result.setData(infoMap);
			}
			HttpServletUtil.writeResponse(request, response, result);
			String responseLog = HttpServletUtil.getResponseLog(request,
					System.currentTimeMillis() - ThreadLocalUtil.getRunTime(), result);
			addUserAccessRecordDat(request, result, null);
			LoggerUtil.info(responseLog);
		}
		setThreadLocalUserId(request);
		ThreadLocalUtil.setIsAuthenticated(null);
		return isAuthenticated;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// execute no.8
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// execute no.9
		Object responseObj = ThreadLocalUtil.getResponseObj();
		String responseLog = HttpServletUtil.getResponseLog(request,
				System.currentTimeMillis() - ThreadLocalUtil.getRunTime(), responseObj);
		try {
			addUserAccessRecordDat(request, responseObj, ex);
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(UserBaseHandlerInterceptor.class.getName(), e);
		}
		LoggerUtil.info(responseLog);
	}

	private void addUserAccessRecordDat(HttpServletRequest request, Object responseObj, Exception ex) throws Exception {
		/*
		 * authType=null, characterEncoding=UTF-8, contentLength=-1,
		 * contentType=null, contextPath=/jites-wechat,
		 * localAddr=0:0:0:0:0:0:0:1, localName=0:0:0:0:0:0:0:1, localPort=8081,
		 * method=GET, pathInfo=null, protocol=HTTP/1.1, queryString=null,
		 * remoteAddr=0:0:0:0:0:0:0:1, remoteHost=0:0:0:0:0:0:0:1,
		 * remotePort=62735, remoteUser=null,
		 * requestURL=http://localhost:8081/jites-wechat/receiver,
		 * requestURI=/jites-wechat/receiver, serverName=localhost,
		 * serverPort=8081, servletPath=/receiver
		 */
//		TblLogSystemUserAccessRecordDat userAccessRecordDat = new TblLogSystemUserAccessRecordDat();
//		userAccessRecordDat.setRecordId(IdGenerator.getId());
//		userAccessRecordDat.setUserId(ThreadLocalUtil.getSessionUserId()); // request.getParameter(ACCESS_UID)
//		ThreadLocalUtil.setSessionUserId("");
//		userAccessRecordDat.setRequestTime((int) (System.currentTimeMillis() - ThreadLocalUtil.getRunTime()));
//		String requestPath = request.getPathInfo();
//		if (StringUtil.isBlank(requestPath)) {
//			requestPath = request.getServletPath();
//		}
//		userAccessRecordDat.setRequestPath(requestPath);
//		userAccessRecordDat.setRequestParam(HttpServletUtil.getRequestParam(request));
//		userAccessRecordDat.setResponse(HttpServletUtil.getResponseContent(responseObj));
//		userAccessRecordDat.setContextPath(request.getContextPath());
//		userAccessRecordDat.setRequestUrl(request.getRequestURL().toString());
//		userAccessRecordDat.setException(HttpServletUtil.getExceptionContent(ex));
//		userAccessRecordDat.setLocalAddr(NetworkUtil.getLocalAddr());
//		userAccessRecordDat.setObjectType(request.getParameter(OBJECT_TYPE));
//		userAccessRecordDat.setObjectId(request.getParameter(OBJECT_ID));
//		userAccessRecordDat.setAccessMode(HttpServletUtil.getAccessMode(request));
//		userAccessRecordDat.setAccessIp(NetworkUtil.getRemoteAddr(request));
//		userAccessRecordDat.setReferer(request.getHeader("referer"));
//		userAccessRecordDat.setSessionId(HttpServletUtil.getSessionId(request));
//		tblLogSystemUserAccessRecordDatMapper.insertSelective(userAccessRecordDat);
	}

	private void setThreadLocalUserId(HttpServletRequest request) {
		String userId = request.getSession().getAttribute("user-Id") + "";
		LoggerUtil.info(">>>> preHandle sessionUserId : " + userId);
		userId = ObjectUtils.defaultIfNull(userId, "");
		if (!StringUtils.isBlank(userId)) {
			if (userId.equals("null")) {
				userId = "";
			}
		}
		ThreadLocalUtil.setSessionUserId(userId);
	}

}
